<template>
     <ul class="list">
           <li
                   class="item" v-for="item of letters"
                   :key="item"
                   :ref="item"
                   @touchstart.prevent="handleTouchStart"
                   @touchmove="handleTouchMove"
                   @touchend="handleTouchEnd"
                   @click="handleLetterClick"
           >
                 {{item}}
           </li>
     </ul>
</template>

<script>
 export default {
  name: "CityAlphabet",
  props:{
   cities: Object
  },
  computed:{
      letters () {
            const  letters=[];
       for(let i in this.cities) {
             letters.push(i)
       }
       return letters
      }
  },
  data () {
      return {
            touchStatus:false,//标识位
            startY:0,
            timer:null
      }
  },
  updated () {/*页面渲染完成时，执行的生命周期函数*/
   this.startY=this.$refs['A'][0].offsetTop /*获得A字母到顶部搜索框的高度*/
  },
  methods:{
   handleLetterClick (e) {
    this.$emit('change',e.target.innerText)
   },
   /*实现拖动右边的字母使页面也活动到对应的位置*/
   handleTouchStart () {
      this.touchStatus=true
   },
   handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {/*函数截流，减少函数的执行频率，提高页面性能*/
            clearTimeout(this.timer)
        }
        this.timer=setTimeout(() => {
             const touchY=e.touches[0].clientY-79;/*获取手指滑动到所在字母的位置到顶端搜索框的高度、79为搜索框的高度*/
             const index=Math.floor((touchY-this.startY)/20);/*获取手指滑动的位置、20位每个字母的高度*/
             if (index >= 0 && index < this.letters.length) {
              this.$emit('change',this.letters[index])
             }
        },16)

      }
   },
   handleTouchEnd () {
    this.touchStatus=false
   }
  }
 }
</script>

<style lang="stylus" scoped>
      @import "../../assets/styles/varibles.styl"
      .list
       display flex
       flex-direction column/*设置或检索弹性盒子元素在主轴方向相反垂直显示*/
       justify-content center/*设置或检索弹性盒子元素在主轴居中*/
       position absolute
       top 1.58rem
       right 0
       bottom 0
       width .4rem
       .item
        line-height .4rem
        text-align center
        color $bgColor
</style>